import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../../utils/common/app_launching.dart';
import '../../../utils/networking/result_analyzed.dart';
import '../../../utils/widget/common.dart';
import '../../../utils/widget/layout_refresh_view.dart';
import '../controllers/login_controller.dart';

class LoginView extends GetView<LoginController> {
  const LoginView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   // title: const NavigationTitle(title: '登录'),
      //   // actions: [navigatorItem("buttonTitle", onTap: ()=> Get.toNamed("/View"))],
      // ),
      body: Column(children: [Obx(() => buildLoadingView())]),
    );
  }

  Widget buildLoadingView() {
    controller.state.value = ResultCode.success;
    return LayoutRefreshView(
      state: controller.state.value,
      onRefresh: controller.onRefresh,
      controller: controller.refreshCtrl,
      child: setupListView(),
    );
  }

  sdsa() {
    return Stack(
      children: [
        Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                  image: AssetImage("assets/login_bg.jpg"),
                  fit: BoxFit.fitHeight
              ),
            )
        ),
        Container(
          color: Colors.black.withOpacity(0.2), // 设置半透明度
        ),
        // 右上角隐藏的快速登录按钮
        Positioned(left: 5, top: 32, child: debugButton()),

        Center(
          child: Container(
            height: 400,
            margin: const EdgeInsets.fromLTRB(20, 10, 20, 0),
            decoration: const BoxDecoration(
              color: Color.fromRGBO(255, 255, 255, 0.85),
              // color: Colors.yellow,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(24),
                  bottomRight: Radius.circular(24)
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    // crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // const Text("图书管理系统", style: TextStyle(fontSize: 28, color: Colors.blue, fontWeight: FontWeight.w700)),
                      const Text("欢迎登录", style: TextStyle(fontSize: 28, color: Colors.blue, fontWeight: FontWeight.w700)),
                      const SizedBox(height: 45),
                      // const Text("请输入账号", style: TextStyle(fontSize: 14, color: Font_Color_grey_153)),
                      SizedBox(height: 50.h, child: controller.accountTextField),
                      const SizedBox(height: 15),
                      SizedBox(height: 50.h, child: controller.passwordTextField),
                    ],
                  ),
                ),
                // Text("我已阅读并同意",style: TextStyle(fontSize: 14, color: Font_Color_Blue_70_135_255)),
                setupPrivacyPolicy(),

                setupLoginButton(),

                Container(
                  height: 50,
                  alignment: Alignment.center,
                  color: Colors.transparent,
                  margin: const EdgeInsets.fromLTRB(30, 15, 30, 0),
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: ()=> Get.toNamed("/RegisterPage"),
                    child: const Text("注册", style: TextStyle(fontSize: 18, color: Font_Color_red)),
                  ),
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget setupListView() {
    // return ListView(
    //   children: [
    //     debugButton(),
    //     setupPhoneNumberTextField(),
    //     setupPasswordTextField(),
    //     setupLoginButton(),
    //   ],
    // );
    // return const Text('你好，世界！', style: TextStyle(fontFamily: 'sans-serif'));
    setupPhoneNumberTextField();
    setupPasswordTextField();
    // setupLoginButton();
    return sdsa();
  }

  setupPhoneNumberTextField() {
    controller.accountTextField = TextField(
      decoration: const InputDecoration(
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Colors.grey, width: 0.5),
        ),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: ThemeColor, width: 0.5),
        ),
        hintText: "请输入账号或手机号",
        hintStyle: TextStyle(color: Colors.grey, fontSize: 20),
      ),
      controller: controller.accountVC,
      // inputFormatters: [
      //   FilteringTextInputFormatter.allow(RegExp('[0-9]')),
      //   FilteringTextInputFormatter.digitsOnly,
      //   phoneInputFormatter(),
      //   LengthLimitingTextInputFormatter(13),
      // ],
      // keyboardType: TextInputType.text,
      // FilteringTextInputFormatter.allow（） (白名单校验)，表示只允许输入符合规则的字符 ;
      // FilteringTextInputFormatter.deny（）（黑名单校验)，除了规定的字符,其他都可以输入;
      // LengthLimitingTextInputFormatter ()，（长度限制）
      // inputFormatters: [
      //   LengthLimitingTextInputFormatter(13),
      //   FilteringTextInputFormatter.allow(
      //     RegExp(regexOnlyNumberText), // 禁止输入空格
      //   )
      // ],
      autocorrect: false,
      style: const TextStyle(color: Colors.black, fontSize: 22),
      onChanged: (value) {
        controller.canLogin.value = controller.accountVC.text.isNotEmpty && controller.passwordVC.text.isNotEmpty;
      },
    );
  }

  setupPasswordTextField() {
   controller.passwordTextField = TextField(
      decoration: const InputDecoration(
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Colors.grey, width: 0.5),
        ),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: ThemeColor, width: 0.5),
        ),
        hintText: "请输入密码",
        hintStyle: TextStyle(color: Colors.grey, fontSize: 20),
      ),
      controller: controller.passwordVC,
      // inputFormatters: [
      //   // FilteringTextInputFormatter.allow(RegExp('[0-9]')),
      //   FilteringTextInputFormatter.digitsOnly,
      //   phoneInputFormatter(),
      //   LengthLimitingTextInputFormatter(13),
      // ],
      autocorrect: false,
      obscureText:true,
      // keyboardType: TextInputType.,
      style: const TextStyle(color: Colors.black, fontSize: 22),
      onChanged: (value) {
        controller.canLogin.value = controller.accountVC.text.isNotEmpty && controller.passwordVC.text.isNotEmpty;
        if (value == ' 1024') { // 切换环境 密码框输入 空格1024 即可
          controller.passwordVC.clear();
          AppLaunching.changeNetworkBaseURL();
        }
      },
    );
  }

  // 隐私协议
  Widget setupPrivacyPolicy() {
    // web 端暂时不用协议
    controller.checkboxSelected.value = true;
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        const SizedBox(width: 20),
        Checkbox(
            shape: const CircleBorder(),// 这⾥就是圆形
            side: const BorderSide(width: 1, color: ThemeColor),
            value: controller.checkboxSelected.value,
            activeColor: ThemeColor, //选中时的颜色
            onChanged:(value) => controller.checkboxClick(value)
        ),

        const Text("已阅读并同意",style: TextStyle(fontSize: 13, color: Colors.black87),),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            Get.toNamed("/WebViewPage", arguments: {
              // "url" : "https://wxapp.91dgj.com/vue/agreement?name=%E6%95%B0%E5%AD%97%E7%A4%BE%E5%8C%BA",
              "url" : "https://echelianhtml.ygxpt.com/agreement/index.html",
              "title" : "服务协议",
            });
          },
          child: const Text("《服务协议》",style: TextStyle(fontSize: 13, color: Colors.blueAccent),),
        ),
        const Text("和",style: TextStyle(fontSize: 13, color: Colors.black87),),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            Get.toNamed("/WebViewPage", arguments: {
              // "url" : "https://wxapp.91dgj.com/vue/ios/privacyProtocol?name=%E6%95%B0%E5%AD%97%E7%A4%BE%E5%8C%BA",
              "url" : "https://echelianhtml.ygxpt.com/privacy/index.html",
              "title" : "隐私政策",
            });
          },
          child: const Text("《隐私政策》",style: TextStyle(fontSize: 13,color: Colors.blueAccent),),
        ),
      ],
    );
  }

  setupLoginButton() {
    return Container(
      height: 50,
      padding: const EdgeInsets.fromLTRB(22, 10, 22, 0),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: ()=> controller.loginClick(),
        child: Obx(() => Container(
          decoration: BoxDecoration(
            color: controller.canLogin.value ? ThemeColor :  Colors.black12,
            borderRadius: const BorderRadius.all(Radius.circular(22)),
          ),
          alignment: Alignment.center,
          padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: Text("登录",style: TextStyle(fontSize: 20, color: controller.canLogin.value ? Colors.white : Colors.black26),),
        )),
      ),
    );
  }

  Widget debugButton() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        color: Colors.transparent,
        alignment: Alignment.topLeft,
        width: 100, height: 80,
      ),
      onTap: ()=> AppLaunching.changeNetworkBaseURL(),
      onDoubleTap: () {
        showAlertDialog(
            title: "联机调试",
            content: Column(
              children: [
                const SizedBox(height: 10,),
                Container(
                  padding: const EdgeInsets.fromLTRB(10, 20, 10, 0),
                  child: MarkView(title: "", controller: controller.hostVC, hintText: "请输入调试主机地址", bgColor: Colors.grey[100]),
                )
              ],
            ),
            confirm: () async {
              if (controller.hostVC.text.isEmpty) { showAlertMessage("请填写取消理由"); return; }
              AppLaunching.changeNetworkBaseURL(host: controller.hostVC.text);
              dismissAlertDialog();
            },
            cancel: () {
              controller.hostVC.text = "";
              dismissAlertDialog();
            }
        );

      },
    );
  }

}